<?php

use yii\db\Migration;

/**
 * Class m181108_062540_init_rbac
 */
class m181108_062540_init_rbac extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->createTable('auth_item', array(
            "name" => 'varchar(64) primary key NOT NULL',
            "type" => 'int',
            "description" => 'text',
            "rule_name" => 'varchar(64)',
            "data" => 'text',
            "created_at" => 'int',
            "updated_at" => 'int',
        ));

        $this->createTable('auth_item_child', array(
            "parent" => 'varchar(64) NOT NULL',
            "child" => 'varchar(64) NOT NULL',
        ));
        $this->createTable('auth_assignment', array(
            "item_name" => 'varchar(64) NOT NULL',
            "user_id" => 'varchar(64) NOT NULL',
            "created_at" => 'int',
        ));

        $auth = Yii::$app->authManager;

        // 添加 "createPost" 权限
        $createPost = $auth->createPermission('createPost');
        $createPost->description = 'Create a post';
        $auth->add($createPost);

        // 添加 "updatePost" 权限
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = 'Update post';
        $auth->add($updatePost);

        // 添加 "author" 角色并赋予 "createPost" 权限
        $author = $auth->createRole('author');
        $auth->add($author);
        $auth->addChild($author, $createPost);

        // 添加 "admin" 角色并赋予 "updatePost" 
		// 和 "author" 权限
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $updatePost);
        $auth->addChild($admin, $author);

        // 为用户指派角色。其中 1 和 2 是由 IdentityInterface::getId() 返回的id
        // 通常在你的 User 模型中实现这个函数。
        $auth->assign($author, 2);
        $auth->assign($admin, 1);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        echo "m181108_062540_init_rbac cannot be reverted.\n";
        $this->dropTable('auth_item');
        $this->dropTable('auth_item_child');
        $this->dropTable('auth_assignment');

        $auth = Yii::$app->authManager;
        $auth->removeAll();
    }

}
